const {
  ui: {
    Label,
    Pane,
    Root,
  },
  util: {
    ansi,
  }
} = require('tui-lib')

const { AppElement } = require('./mtui/ui')
const processSmartPlaylist = require('./mtui/smart-playlist')

async function main() {
  const WebInterfacer = require('./WebInterfacer')

  const canvas = document.getElementById('output')
  const interfacer = new WebInterfacer(canvas)

  const size = interfacer.getScreenSize()

  const root = new Root(interfacer)
  root.w = size.width
  root.h = size.height

  /*
  const pane = new Pane()
  root.addChild(pane)
  pane.fillParent()

  const label = new Label('Hello, world!')
  label.textAttributes = [ansi.C_BLUE]
  pane.addChild(label)
  */

  const appElement = new AppElement()
  await appElement.setup()
  root.addChild(appElement)
  root.select(appElement)



  let grouplike = {
    name: 'My Web-MTUI Library',
    comment: `(You're running the magical WEB MTUI!! Try pressing Ctrl-O to open a playlist.)`
  }

  grouplike = await processSmartPlaylist(grouplike)

  appElement.tabber.currentElement.loadGrouplike(grouplike)

  window.interfacer = interfacer
  window.root = root
  window.appElement = appElement

  const interval = setInterval(() => {
    try {
      root.renderTo(interfacer.flushable)
      interfacer.flushable.flush()
    } catch (error) {
      clearInterval(interval)
      throw error
    }
  }, 100)

  await appElement.handlePlaylistSource('http://192.168.2.31:1233/', true)
  //await appElement.handlePlaylistSource('playlist.json', true)
  //await appElement.handlePlaylistSource('https://cors-anywhere.herokuapp.com/billwurtz.com/songs.html', true)
}

main()
  .catch(error => console.error(error))
